package cn.ztuo.bitrade.controller;

import cn.ztuo.bitrade.constant.BooleanEnum;
import cn.ztuo.bitrade.constant.MemberLevelEnum;
import cn.ztuo.bitrade.entity.*;
import cn.ztuo.bitrade.entity.transform.AuthMember;
import cn.ztuo.bitrade.service.*;
import cn.ztuo.bitrade.util.BigDecimalUtils;
import cn.ztuo.bitrade.util.Md5;
import cn.ztuo.bitrade.util.MessageResult;
import cn.ztuo.bitrade.vo.EarningsBuyRecordVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.math.BigDecimal;

import static cn.ztuo.bitrade.constant.SysConstant.SESSION_MEMBER;

/**
 * @author: Xiazt
 * @date: 2020-04-09 10:36
 */
@Slf4j
@RestController
@RequestMapping("/earningsTreasure")
public class EarningsTreasureController extends BaseController {

    @Autowired
    private EarningsTreasureService earningsTreasureService;

    @Autowired
    private EarningsBuyRecordService earningsBuyRecordService;

    @Autowired
    private MemberService memberService;

    @Autowired
    private MemberWalletService memberWalletService;

    @Autowired
    private CoinService coinService;
    @Autowired
    private BourseProductManagerService productManagerService;
    @Autowired
    private LocaleMessageSourceService msService;

    /**
     * 获取收益宝列表
     *
     * @return
     */
    @RequestMapping(value = "getEarningsTreasureList")
    public MessageResult getEarningsTreasureList() {
        return success(earningsTreasureService.findAllByStatus());
    }


    @RequestMapping("getMyEarningsTreasure")
    public MessageResult getMyEarningsTreasure(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,
                                               @RequestParam( value = "pageNum",defaultValue = "1") Integer pageNum,
                                               @RequestParam( value = "pageSize",defaultValue = "10") Integer pageSize,
                                               Integer status) {

        EarningsBuyRecordVO earningsBuyRecordVO = new EarningsBuyRecordVO();
        earningsBuyRecordVO.setMemberId(authMember.getId());
        earningsBuyRecordVO.setPageNum(pageNum);
        earningsBuyRecordVO.setPageSize(pageSize);
        earningsBuyRecordVO.setStatus(status);

        return success(earningsBuyRecordService.getByPage(earningsBuyRecordVO));

    }

    /**
     * 购买收益宝
     *
     * @param authMember
     * @param earningTreasureId
     * @param aomunt
     * @param jyPassword
     * @return
     */
    @RequestMapping(value = "buyEarningsTreasure")
    public MessageResult buyEarningsTreasure(@SessionAttribute(SESSION_MEMBER) AuthMember authMember,
                                             Long earningTreasureId,
                                             BigDecimal aomunt,
                                             String jyPassword) {
        try {
            //判断该产品是否关闭
            BourseProductManager productManager = productManagerService.getByProductCode("0500");
            if(productManager.getStatus()==0){
                return MessageResult.error(500, msService.getMessage("PRODUCT_CLOSE"));
            }
            if (jyPassword == null || jyPassword.equals("")) return error("交易密码不能为空！");
            //验证用户信息
            Member member = memberService.findOne(authMember.getId());
            if (member.getTransactionStatus().equals(BooleanEnum.IS_FALSE)) return error("您当前账户已禁用，请联系客服！");
            if (member.getMemberLevel() == MemberLevelEnum.GENERAL) error("请先进行实名认证！");

            //验证交易密码
            String mbPassword = member.getJyPassword();
            if (mbPassword == null || mbPassword.equals("")) return MessageResult.error(500, "请先设置交易密码！");
            if (!Md5.md5Digest(jyPassword + member.getSalt()).toLowerCase().equals(mbPassword))
                return MessageResult.error(500, "交易密码错误！");
            EarningsTreasure earningsTreasure = earningsTreasureService.getById(earningTreasureId);
            //验证状态 0已结束，1出售中，2未开始
            if (earningsTreasure.getStatus() != 1) return error(500, "该活动未开启或已结束！");

            // 验证购买数量
            int min = aomunt.compareTo(earningsTreasure.getMinBuyAomunt());
            int max = aomunt.compareTo(earningsTreasure.getMaxBuyAomunt());
            if (min < 0) return error(500, "不满足最小购买数量");
            if (max > 0) return error(500, "超过最大购买数量");
            // 计算剩余数量
            BigDecimal residueAomunt = BigDecimalUtils.sub(earningsTreasure.getTotalAomunt(), earningsTreasure.getSoldAomunt());
            if (!BigDecimalUtils.compare(residueAomunt, aomunt)) return error(500, "剩余数量不足");
            // 验证账户余额
            Coin coin = coinService.findOne(earningsTreasure.getCoin().getName());
            MemberWallet memberWallet = memberWalletService.findByCoinAndMember(coin, member);
            int balance = aomunt.compareTo(memberWallet.getBalance());
            if (balance > 0) return error(500, "账户余额不足");

            // 业务
            return earningsBuyRecordService.buyEarningsTreasure(earningsTreasure, member, memberWallet, aomunt);

        } catch (Exception e) {
            e.printStackTrace();
            return error("服务器异常！");
        }
    }
}
